//
//  HTStatisticsViewController.m
//  HappyTravel
//
//  Created by Apple on 2018/8/2.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "HTStatisticsViewController.h"
#import <PGDatePicker/PGDatePickManager.h>
#import "StaticsView.h"

@interface HTStatisticsViewController () <PGDatePickerDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITextField *dropDownTextField;
@property (nonatomic, strong) StaticsView *staticsView;

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *monthArr;

@end

@implementation HTStatisticsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = ThemeColor;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:COLOR_RGB(255, 255, 255)}];
    
    [self loadData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"Statistics";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self setupUI];
}

#pragma mark - CustomMethod
- (void)loadData {
    
    [self.dataArr removeAllObjects];
    self.dataArr = [HTSingleton readModelArrayForDocument:TravelModelPath];
    [self comapreWithMonth:self.dropDownTextField.text];
    [self getHasBeenCity];
    [self getStaticsHeight];
    [self getAverageMonthly];
}

#pragma mark - 每月平均旅行次数
- (void)getAverageMonthly {
    CGFloat average = self.monthArr.count/12.0;
    self.staticsView.averageMonth.text = [NSString stringWithFormat:@"%.2f",average];
}

#pragma mark - 获取当年的去过的城市个数和去过的最多的城市
- (void)getHasBeenCity {
    
    /**
     得到去过的城市个数
     */
    NSMutableArray *allCityArr = [[NSMutableArray alloc]init];
    for (TralvelModel *model in self.monthArr) {
        [allCityArr addObject:model.endLocation];
    }
    NSMutableArray *listAry = [[NSMutableArray alloc]init];
    for (NSString *str in allCityArr) {
        if (![listAry containsObject:str]) {
            [listAry addObject:str];
        }
    }
    self.staticsView.allCity.text = [NSString stringWithFormat:@"%lu",(unsigned long)listAry.count];
    
    
    
    /**
     得到去过最多城市
     */
    NSInteger maxSameObj = 0;
    NSString *cithName;
    
    NSSet *set = [NSSet setWithArray:allCityArr];
    for (NSString *setstring in set) {
        //需要去掉的元素数组
        NSMutableArray *filteredArray = [[NSMutableArray alloc]initWithObjects:setstring, nil];
        NSMutableArray *dataArray = allCityArr;
        NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",filteredArray];
        //过滤数组
        NSArray * reslutFilteredArray = [dataArray filteredArrayUsingPredicate:filterPredicate];
        int number = (int)(dataArray.count-reslutFilteredArray.count);
        
        maxSameObj = maxSameObj > number?maxSameObj:number;
        if (maxSameObj > number) {
            maxSameObj = maxSameObj;
        }else {
            maxSameObj = number;
            cithName = setstring;
        }
    }
    self.staticsView.mostCity.text = cithName;
}

#pragma mark - 获取数据比例显示
- (void)getStaticsHeight {
    
    NSMutableArray *heightArr = [[NSMutableArray alloc] init];
    
    for (int i = 1; i < 13; i ++) {
        NSString *currentMonth = [NSString stringWithFormat:@"%d",i];
        NSString *yearAndMonth = [NSString stringWithFormat:@"%@-%@",self.dropDownTextField.text,currentMonth];
        NSInteger allMonth = 0;
        for (TralvelModel *model in self.monthArr) {
            int  comapre = [self comapreDateAndMonth:yearAndMonth anotherDate:model.date andFormat:@"yyyy-M" ansRangeInt:6];
            if (comapre == 0){
                allMonth ++;
            }
        }
        
        NSInteger height = 15;
        if (allMonth == 0) {
            allMonth = 1;
        }else {
            allMonth = allMonth + 1;
        }
        
        if (15*allMonth > 171) {
            height = 171;
        }else {
            height = 15*allMonth;
        }
        
        [heightArr addObject:[NSString stringWithFormat:@"%ld",(long)height]];
    }
    
    self.staticsView.januaryHeight.constant = [heightArr[0] integerValue];
    self.staticsView.februaryHeight.constant = [heightArr[1] integerValue];
    self.staticsView.marchHeight.constant = [heightArr[2] integerValue];
    self.staticsView.aprilHeight.constant = [heightArr[3] integerValue];
    self.staticsView.mayHeight.constant = [heightArr[4] integerValue];
    self.staticsView.juneHeight.constant = [heightArr[5] integerValue];
    self.staticsView.julyHeight.constant = [heightArr[6] integerValue];
    self.staticsView.augustHeight.constant = [heightArr[7] integerValue];
    self.staticsView.septemberHeight.constant = [heightArr[8] integerValue];
    self.staticsView.octoberHeight.constant = [heightArr[9] integerValue];
    self.staticsView.novemberHeight.constant = [heightArr[10] integerValue];
    self.staticsView.decemberHeight.constant = [heightArr[11] integerValue];
}


#pragma mark - 获取选中的当年的所有数据
- (void)comapreWithMonth:(NSString *)date{
    
    [self.monthArr removeAllObjects];
    for (TralvelModel *model in self.dataArr) {
        int  comapre = [self comapreDate:date anotherDate:model.date andFormat:@"yyyy" ansRangeInt:4];
        if (comapre == 0){
            [self.monthArr addObject:model];
        }
    }
}

-(int )comapreDate:(NSString *)date anotherDate:(NSString *)anotherDate andFormat:(NSString *)format ansRangeInt:(NSInteger)range{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSDate *dates = [dateFormatter dateFromString:date];
    anotherDate = [anotherDate substringWithRange:NSMakeRange(0, range)];
    NSDate *another = [dateFormatter dateFromString:anotherDate];
    
    NSComparisonResult result = [dates compare:another];
    if (result == NSOrderedDescending) {
        return 1;
    }else if(result ==NSOrderedSame){
        return 0;
    }else {
        return -1;
    }
}

-(int )comapreDateAndMonth:(NSString *)date anotherDate:(NSString *)anotherDate andFormat:(NSString *)format ansRangeInt:(NSInteger)range{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-M-dd HH:mm"];
    NSDate *newAnother = [dateFormatter dateFromString:anotherDate];
    
    NSDateFormatter *dateFormatter11 = [[NSDateFormatter alloc] init];
    [dateFormatter11 setDateFormat:format];
    
    NSDate *dates = [dateFormatter11 dateFromString:date];
    NSString *another = [dateFormatter11 stringFromDate:newAnother];
    NSDate *anotherNewDate = [dateFormatter11 dateFromString:another];
    
    NSComparisonResult result = [dates compare:anotherNewDate];
    if (result == NSOrderedDescending) {
        return 1;
    }else if(result ==NSOrderedSame){
        return 0;
    }else {
        return -1;
    }
}


- (void)setupUI {
    
    [self.view addSubview:self.dropDownTextField];
    [self.view addSubview:self.staticsView];
    
    [self.staticsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(113);
    }];
    
    self.staticsView.septemberHeight.constant = 100;
    self.staticsView.mayHeight.constant = 15;
    self.staticsView.januaryHeight.constant = 150;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.datePickerMode = PGDatePickerModeYear;
    datePicker.rowHeight = 40;
    datePicker.delegate = self;
    [self presentViewController:datePickManager animated:false completion:nil];
    
    return NO;
}

#pragma mark - PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    
    self.dropDownTextField.text = [NSString stringWithFormat:@"%ld",(long)dateComponents.year];
    [self loadData];
}

#pragma mark - getter
- (UITextField *)dropDownTextField {
    return _dropDownTextField ?: ({
        _dropDownTextField = [[UITextField alloc]initWithFrame:CGRectMake(ScreenWidth-80-20, 23+SafeAreaTopHeight, 80, 25)];
        _dropDownTextField.text = [HTSingleton getCurrentYear];
        _dropDownTextField.textColor = UIColorOfHex(0x3B3C4A);
        _dropDownTextField.textAlignment = NSTextAlignmentCenter;
        _dropDownTextField.font = [UIFont systemFontOfSize:14];
        _dropDownTextField.delegate = self;
        
        UIButton *dropBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 16)];
        [dropBtn setImage:[UIImage imageNamed:@"drop"] forState:UIControlStateNormal];
        dropBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _dropDownTextField.rightView = dropBtn;
        _dropDownTextField.rightViewMode = UITextFieldViewModeAlways;
        
        _dropDownTextField.layer.borderColor = UIColorOfHex(0x3B3C4A).CGColor;
        _dropDownTextField.layer.borderWidth = 1.0f;
        _dropDownTextField.layer.cornerRadius = 10;
        _dropDownTextField;
    });
}

- (StaticsView *)staticsView {
    if (!_staticsView) {
        _staticsView = [[[NSBundle mainBundle] loadNibNamed:@"StaticsView" owner:self options:nil] lastObject];
    }
    return _staticsView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

- (NSMutableArray *)monthArr {
    if (!_monthArr) {
        _monthArr = [[NSMutableArray alloc] init];
    }
    return _monthArr;
}


@end
